package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.BoreholeConditionInputDto;
import com.b511.swpu.cementbackend.entity.FormationTemperature;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.FormationTemperatureRepository;
import com.b511.swpu.cementbackend.service.FormationTemperatureService;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.CopyUtil;
import com.b511.swpu.cementbackend.util.R;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class FormationTemperatureServiceImpl implements FormationTemperatureService {

    private final FormationTemperatureRepository formationTemperatureRepository;

    public FormationTemperatureServiceImpl(FormationTemperatureRepository formationTemperatureRepository) {
        this.formationTemperatureRepository = formationTemperatureRepository;
    }

    @Override
    public R getFormationTemperatureByCondition(BoreholeConditionInputDto boreholeConditionInputDto, PageRequest pageRequest) {
        return R.ok().putData(formationTemperatureRepository.findAll());
    }

    @Override
    @Transactional
    public R updateFormationTemperature(Long id, FormationTemperature updateFormationTemperature) {
        Optional<FormationTemperature> optionalFormationTemperature = formationTemperatureRepository.findById(id);
        if(!optionalFormationTemperature.isPresent()) {
            throw new CementException(Code.SELECT_FAIL);
        }
        FormationTemperature formationTemperature = optionalFormationTemperature.get();
        CopyUtil.copyProperties(updateFormationTemperature,formationTemperature);
        formationTemperatureRepository.save(formationTemperature);
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteFormationTemperature(Long id) {
        formationTemperatureRepository.deleteById(id);
        return R.ok();
    }
}
